package com.clstu.qqclient.qqframe;

import com.clstu.qqclient.service.UserClientService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * 这是一个显示登录界面的类
 */

public class LoginFrame extends JFrame implements ActionListener, KeyListener {

    private JLabel idLb = new JLabel("请输入账号");
    private JTextField id = new JTextField(10);
    private JLabel pwdLb = new JLabel("请输入密码");
    private JPasswordField pwd = new JPasswordField(10);
    private JButton btLogin = new JButton("登录");
    private JButton btRegister = new JButton("注册");
    private JButton btExit = new JButton("退出");
    private UserClientService userClientService = new UserClientService();//用于判断是否登录成功的成员


    public LoginFrame(){

        super("登录");//窗口名称
        this.setLayout(new FlowLayout());//设置流式布局

        this.add(idLb);//在窗口中加入这些成员组件
        this.add(id);
        this.add(pwdLb);
        this.add(pwd);
        this.add(btLogin);
        this.add(btRegister);
        this.add(btExit);

        this.setSize(260,190);//设置一些窗口属性
        this.setLocation(700,400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setVisible(true);

        pwd.addKeyListener(this);
        btExit.addActionListener(this);//给各个按钮加入监听器
        btLogin.addActionListener(this);
        btRegister.addActionListener(this);

    }

    public void login(){
        String id = this.id.getText();
        String pwd = new String(this.pwd.getPassword());

        if(userClientService.checkUser(id,pwd)){//登录成功
            JOptionPane.showMessageDialog(this,"登录成功");
            this.dispose();
            new MainMenu(id);
        }else {
            JOptionPane.showMessageDialog(this, "登录失败");
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {//事件监听的处理

        if(e.getSource()==btLogin){//如果是登录
            login();
        }else if(e.getSource()==btRegister){//如果是注册
            this.dispose();
            new RegisterFrame();
        }else {
            JOptionPane.showMessageDialog(this,"谢谢光临");
            System.exit(0);
        }

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
         if(e.getKeyCode() == KeyEvent.VK_ENTER){
             login();
         }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}
